package com.zxy.ziems.server.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.btp.common.exception.ConditionException;
import com.zxy.ziems.server.constant.ClassifyCountType;
import com.zxy.ziems.server.classify.pojo.entity.Classify;
import com.zxy.ziems.server.domain.ClassifyPointRel;
import com.zxy.ziems.server.dto.ClassifyPointRelDeleteDto;
import com.zxy.ziems.server.dto.ClassifyPointRelDto;
import com.zxy.ziems.server.dto.PointRelDto;
import com.zxy.ziems.server.classify.mapper.ClassifyMapper;
import com.zxy.ziems.server.mapper.ClassifyPointRelMapper;
import com.zxy.ziems.server.service.ClassifyPointRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ClassifyPointRelServiceImpl
 * @Description
 * @Author 邓伟
 * @Date 2023/11/27 14:47
 * @Version 1.0
 */
@Service
public class ClassifyPointRelServiceImpl extends ServiceImpl<ClassifyPointRelMapper, ClassifyPointRel> implements ClassifyPointRelService {

    @Autowired
    private ClassifyPointRelMapper classifyPointRelMapper;
    @Autowired
    private ClassifyMapper classifyMapper;

    @Override
    public void bindPoint(ClassifyPointRelDto classifyPointRelDto) {
        //查询根节点id
        String classifyId = classifyPointRelDto.getClassifyId();
        Classify classify = classifyMapper.selectById(classifyId);
        if (ObjectUtil.isEmpty(classify)) {
            throw new ConditionException("未找到此分类");
        }
        Integer countType = classify.getCountType();
        if (ClassifyCountType.CLASSIFY_COUNT == countType) {
            throw new ConditionException("计算方式为下级分类合计时，不允许添加点位");
        }
        List<ClassifyPointRel> list = new ArrayList<>();
        List<PointRelDto> pointList = classifyPointRelDto.getPointList();
        for (PointRelDto pointRelDto : pointList) {
            ClassifyPointRel classifyPointRel = new ClassifyPointRel();
            classifyPointRel.setClassifyId(classifyId);
            classifyPointRel.setPointId(pointRelDto.getPointId());
            classifyPointRel.setPointCode(pointRelDto.getPointCode());
            classifyPointRel.setRootClassifyId(classify.getRootClassifyId());
            classifyPointRel.setDataObtainType(classify.getDataObtainType());
            list.add(classifyPointRel);
        }
        saveBatch(list);
    }

    @Override
    public void delete(ClassifyPointRelDeleteDto relDto) {
        QueryWrapper<ClassifyPointRel> query = new QueryWrapper<>();
        query.lambda().eq(ClassifyPointRel::getPointId,relDto.getPointId())
                .eq(ClassifyPointRel::getClassifyId,relDto.getClassifyId());
        classifyPointRelMapper.delete(query);
    }
}
